package com.emm.yixun.jobs;

import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.TelRecord;
import com.emm.yixun.common.model.dto.TelRecordDto;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.soap.client.NetworkTelephoneClient;
import com.emm.yixun.system.service.TelRecordServiceFacade;
/**
* 类描述： 同步电话平台话单
* 创建者： ym
* 项目名称： emm-jobs
 */
@Component
public class GrabTelRecordJob {
	private static Logger logger = LoggerFactory.getLogger(GrabTelRecordJob.class);
	
	@Autowired
	private TelRecordServiceFacade telRecordServiceFacade;
	
	@Value("${quartz.cron.grabTelRecordPageSize}")
	private Integer grabTelRecordPageSize;
	
	@Scheduled(cron="${quartz.cron.grabTelRecordJob}")
	public void grabTelRecord(){
		/**
		*1.查找通话记录。条件为：通话状态=待获取
		*2.调用电话平台接口同步更新通话记录
		*/
		logger.info("......同步电话平台话单启动......");
		List<TelRecord> list=queryTelRecordList();
		handerTelRecord(list);
		logger.info("......同步电话平台话单结束......");
	}
	//查找通话记录。条件为：通话状态=待获取
	private List<TelRecord> queryTelRecordList(){
		List<TelRecord> list=new ArrayList<TelRecord>();
		TelRecordDto telRecordDto=new TelRecordDto();
		telRecordDto.setCallStatus("0");
		ResponseList<TelRecord> responseList=telRecordServiceFacade.findByDto(telRecordDto);
		if(responseList.isSuccess() && null!=responseList.getEntity()){
			list=responseList.getEntity();
		}
		logger.info("......符合条件的通话记录："+list.size()+"条......");
		return list;
	}
	
	private void handerTelRecord(List<TelRecord> list){
		logger.info("......调用电话平台接口同步更新通话记录启动......");
		int total=list.size();//总条数
		int pageNum=1;//当前页
		int pageSize=50;//每页条数
		if(null!=grabTelRecordPageSize){
			pageSize=grabTelRecordPageSize;//每页条数
		}
		
		int totalPages=0;//总页数
		if(pageSize>0&&total%pageSize==0){
			totalPages = total/pageSize;
		}else{
			totalPages = (total - total%pageSize)/pageSize + 1;
		}
		while(totalPages>=pageNum){
			int start=PageUtil.begin(pageNum, pageSize);
			int end=start+pageSize;
			if(end>list.size())end=list.size();
			List<TelRecord> handerList=new ArrayList<TelRecord>();
			StringBuffer sb=new StringBuffer();
			for(int i=start;i<end;i++){
				TelRecord trd=list.get(i);
				if(i>start){
					sb.append(",");
				}
				sb.append(trd.getUniqueId());
				handerList.add(trd);
			}
			//调用接口并同步更新通话记录
			syncTelRecordList(sb.toString(),handerList);
			pageNum++;
		}
		logger.info("......调用电话平台接口同步更新通话记录结束......");
	} 
	
	private void syncTelRecordList(String uniqueIds,List<TelRecord> handerList){
		JSONObject object=NetworkTelephoneClient.getCallRecord(uniqueIds);
		JSONArray dataList=object.getJSONArray("dataList");
		if(null==dataList || dataList.size()==0)return;
		for(int i=0;i<dataList.size();i++){
			JSONObject rowData=dataList.getJSONObject(i);
			//唯一编码
			String uniqueId=rowData.getString("uniqueId");
			TelRecord tr=findTelRecord(uniqueId,handerList);
			if(null==tr)continue;
			//1 3 4 才算接通 
			String byType=rowData.getString("byType");
			//通话时长
			int billableSeconds=rowData.getIntValue("billableSeconds");
			//主叫接通时间
			String answerTime=rowData.getString("answerTime");
			//被叫接通时间
			String bridgeTime=rowData.getString("bridgeTime");
			//通话开始时间
			String startTime=rowData.getString("startTime");
			//通话结束时间
			String endTime=rowData.getString("endTime");
			//录音地址
			String recordUrl=rowData.getString("recordUrl");

			//更新通话记录
			TelRecordDto trd=new TelRecordDto();
			trd.setId(tr.getId());
			trd.setBillableSeconds(billableSeconds);
			if(billableSeconds>0 && StringUtils.isNotBlank(answerTime) && StringUtils.isNotBlank(bridgeTime)){
				trd.setCallStatus("1");
			}else{
				trd.setCallStatus("2");
			}
			if(StringUtils.isNotBlank(answerTime)){
				trd.setAnswerTime(DateUtils.StringToDate(answerTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
			}
			if(StringUtils.isNotBlank(bridgeTime)){
				trd.setBridgeTime(DateUtils.StringToDate(bridgeTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
			}
			if(StringUtils.isNotBlank(startTime)){
				trd.setStartTime(DateUtils.StringToDate(startTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
			}
			if(StringUtils.isNotBlank(endTime)){
				trd.setEndTime(DateUtils.StringToDate(endTime, DateStyle.YYYY_MM_DD_HH_MM_SS));
			}
			
			if(StringUtils.isNotBlank(recordUrl)){
				trd.setRecordUrl(recordUrl);
			}
			telRecordServiceFacade.updateByPrimaryKey(trd, true);
		}
	}
	
	private TelRecord findTelRecord(String uniqueId,List<TelRecord> handerList){
		for(TelRecord tr : handerList){
			if(StringUtils.isNotBlank(tr.getUniqueId()) && tr.getUniqueId().equals(uniqueId)){
				return tr;
			}
		}
		return null;
	}
}
